import com.intellij.designer.clipboard.SimpleTransferable;
import com.intellij.icons.AllIcons;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.TreeFileChooser;
import com.intellij.ide.util.TreeFileChooserFactory;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import org.apache.commons.compress.utils.Lists;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.util.List;

public class HelloWorldAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // TODO: insert action logic here

        System.out.println("hello world!");
        //获取当前在操作的工程上下文
        Project project = e.getData(PlatformDataKeys.PROJECT);

        //获取当前操作的类文件
        PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);

        Object a = psiFile.getContainingDirectory();
        Object b = psiFile.getFileElementType();
        Object c = psiFile.getFileType();
        Object d = psiFile.getNode();
        Object f = psiFile.getContainingFile();

        //获取当前类文件的路径
        String classPath = psiFile.getVirtualFile().getPath();
        String title = "Hello World!";


//        if (isJavaClass(e, project)) return;
//
//
//        showChooser(e, project, psiFile, title);

//        saveConfig(project, title);
//
//        SampleDialogWrapper sdw = new SampleDialogWrapper(project, "自己创建的对话框");
//        sdw.show();


//        noitfy();

    }

    private void noitfy() {
        Notification n = new Notification("hello", AllIcons.General.InspectionsOK, NotificationType.WARNING);
        n.setTitle("Hwllo");
        n.setContent("hss");
        n.setContextHelpAction(this);
        Notifications.Bus bus = new Notifications.Bus();

        bus.notify(n);
    }

    /**
     * 储存持久化对象 (project级别)
     *
     * @param project
     * @param title
     */
    private void saveConfig(Project project, String title) {
        PropertiesComponent pc = PropertiesComponent.getInstance(project);

        String value = pc.getValue("wm.hw.helloworld!");

        Messages.showMessageDialog(project, value, title, Messages.getInformationIcon());

        pc.setValue("wm.hw.helloworld!", "hello!!!!!!");
    }

    /**
     * 展示一个文件选取器, 最终得到一个选中的psi文件.
     *
     * @param e
     * @param project
     * @param psiFile
     * @param title
     */
    private void showChooser(AnActionEvent e, Project project, PsiFile psiFile, String title) {
        //显示对话框
        TreeFileChooser tfc = TreeFileChooserFactory.getInstance(e.getProject()).createFileChooser("hello", psiFile, JavaFileType.INSTANCE, null);

        tfc.showDialog();

        psiFile = tfc.getSelectedFile();

        Messages.showMessageDialog(project, psiFile.getText(), title, Messages.getInformationIcon());
    }


    /**
     * 判断是否是java类
     *
     * @param e
     * @param project
     * @return
     */
    private boolean isJavaClass(AnActionEvent e, Project project) {
        //获取当前事件触发时，光标所在的元素
        PsiElement psiElement = e.getData(LangDataKeys.PSI_ELEMENT);
        //如果光标选择的不是类，弹出对话框提醒
        if (psiElement == null || !(psiElement instanceof PsiClass)) {
            Messages.showMessageDialog(project, "Please focus on a class", "Generate Failed", null);
            return true;
        }
        return false;
    }


    /**
     * 获取当前类文件的所有类对象
     *
     * @param element
     * @return
     */
    public static List<PsiClass> getClasses(PsiElement element) {
        List<PsiClass> elements = Lists.newArrayList();
        List<PsiClass> classElements = PsiTreeUtil.getChildrenOfTypeAsList(element, PsiClass.class);
        elements.addAll(classElements);
        for (PsiClass classElement : classElements) {
            //这里用了递归的方式获取内部类
            elements.addAll(getClasses(classElement));
        }
        return elements;
    }

    /**
     * 格式化代码
     *
     * @param theElement
     */
    public static void reformatJavaFile(PsiElement theElement) {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(theElement.getProject());
        try {
            codeStyleManager.reformat(theElement);
        } catch (Exception e) {
//            LOGGER.error("reformat code failed", e);
        }
    }

    /**
     * 将内容复制到剪贴板
     *
     * @param content
     */
    public void copyPaste(String content) {
        CopyPasteManager.getInstance()
                .setContents(new SimpleTransferable(content, DataFlavor.allHtmlFlavor));
    }


    /**
     * 演示一个标准对话框的展示, 里面俩按钮.其中一个带事件并弹出新的对话框.
     */
    public class SampleDialogWrapper extends DialogWrapper {

        private Project project;

        private String title;

        public SampleDialogWrapper(final Project project, final String title) {
            super(project, true); // use current window as parent
            init();
            setTitle(title);

            this.project = project;
            this.title = title;
        }

        @Nullable
        @Override
        protected JComponent createCenterPanel() {
            JPanel dialogPanel = new JPanel(new BorderLayout());

            JLabel label = new JLabel("testing");
            label.setPreferredSize(new Dimension(100, 100));
            dialogPanel.add(label, BorderLayout.CENTER);

            JButton testButton = new JButton();
            testButton.setText("弹出自己");
            testButton.addActionListener(actionEvent -> {
                if (new SampleDialogWrapper(project, title).showAndGet()) {
                    // user pressed ok
                }
            });
            dialogPanel.add(testButton, BorderLayout.CENTER);


            return dialogPanel;
        }
    }
}
